import config from './config.js';
import request from '../api/request.js'

// 图片上传
function uploadFile(url, file) {
	uni.showLoading({
		title: '图片上传中'
	})
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: config.baseUrl + url,
			filePath: file,
			name: 'file',
			dataType: "json",
			success: function(uploadFileRes) {
				if (uploadFileRes.data) {
					var type = typeof uploadFileRes.data;
					if (type == 'string') {
						uploadFileRes.data = JSON.parse(uploadFileRes.data)
					}
					resolve(uploadFileRes.data);
				}
			},
			fail: function(res) {
				console.log(res)
			},
			complete: function() {
				uni.hideLoading();
			}
		})
	})
}


// 图片上传2
function uploadFiles(file) {
	const bid = uni.getStorageSync('bid');
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: config.baseUrl + `/zzjApp/uploade?bid=${bid}`,
			filePath: file,
			name: 'file',
			dataType: "json",
			success: function(uploadFileRes) {
				if (uploadFileRes.data) {
					if (typeof uploadFileRes.data != 'object') {
						uploadFileRes.data = JSON.parse(uploadFileRes.data)
					}
					resolve(uploadFileRes.data);
				}

			},
			fail: function(res) {
				console.log(res)
			},
			complete: function() {

			}
		})
	})
}
// import HTMLParser from "./html-parser.js"

function richTxt(html) {
	var capture = html,
		array = [];
	var i = -1;
	if (html) {
		html = capture.replace(/src=\s*['"]([^'"]+)[^>]*>/gi, function(match, capture) {
				i++;
				if (capture.indexOf('http') > -1) {
					array.push(capture);
					capture = ' src="' + capture +
						'" style="max-width: 100%; height: auto; margin: 0 auto; display: block;" data-index=' + i +
						' />';
					console.log(capture)
					return capture
				} else {
					array.push(config.imgUrl + capture);
					capture = ' src="' + config.imgUrl + capture +
						'" style="max-width: 100%; height: auto; margin: 0 auto; display: block;" data-index=' + i +
						' />';
					return capture
				}
			})
			.replace(/<section/g, '<div').replace(/\/section>/g, '/div>')
			.replace(/<o:p>/g, '').replace(/<\/o:p>/g, '')
			.replace(/<font/g, '<span').replace(/\/font>/g, '/span>')
		// html = new HTMLParser(html.trim());
	}
	var obj = {
		html: html,
		imgs: array
	};
	return obj;
}

function Tel(phone) {
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	} else {
		uni.showToast({
			title: "很抱歉，暂未配置联系电话！",
			icon: 'none'
		})
	}
}

function call() {
	let phone = uni.getStorageSync('startUp').service_tel;
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	} else {
		uni.showToast({
			title: "很抱歉，暂未配置联系电话！",
			icon: 'none'
		})
	}

}

function toUrl(url) {
	uni.navigateTo({
		url: url
	})
}

function back(time) {
	uni.navigateBack({
		delta: time ? time : 1
	})
}

function showToast(txt) {
	uni.showToast({
		title: txt,
		icon: 'none',
		duration: 1500
	})
}


function Toast(msg, state = 1, url) {
	if (state == 1) {
		uni.showToast({
			title: msg,
			icon: 'none',
		})
	} else if (state == 2) {
		uni.showToast({
			title: msg,
			mask: true,
			icon: 'none',
			success: () => {
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 800)

			}
		})
	} else if (state == 3) {
		uni.showToast({
			title: msg,
			mask: true,
			icon: 'none',
			success: () => {
				setTimeout(() => {
					uni.redirectTo({
						url: url
					})
				}, 800)

			}
		})
	} else if (state == 4) {
		uni.showToast({
			title: msg,
			icon: 'none',
			mask: true,
			duration: 2000
		})
	} else if (state == 5) {
		uni.showToast({
			title: msg,
			icon: 'none',
			mask: true,
			duration: 3000
		})
	}
}

function toGoods(goods_id, type, state) {
	uni.navigateTo({
		url: '/pages/goods/goodsDetail?goodsid=' + goods_id
	})
}

function backHome() {
	uni.reLaunch({
		url: '/pages/index/index'
	})
}


function timeFormat(number, format) {
	/** 
	 * 时间戳转化为年 月 日 时 分 秒 
	 * number: 传入时间戳 
	 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
	 */
	function formatTime(number, format) {
		var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
		var returnArr = [];
		var date = new Date(number * 1000);
		returnArr.push(date.getFullYear());
		returnArr.push(formatNumber(date.getMonth() + 1));
		returnArr.push(formatNumber(date.getDate()));

		returnArr.push(formatNumber(date.getHours()));
		returnArr.push(formatNumber(date.getMinutes()));
		returnArr.push(formatNumber(date.getSeconds()));

		for (var i in returnArr) {
			format = format.replace(formateArr[i], returnArr[i]);
		}
		return format;
	}

	//数据转化  
	function formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
	return formatTime(number, format);
}

// 图片预览
function previewImage(i, imgArry) {
	if (imgArry) {
		let arr = [];
		for (let i in imgArry) {
			arr.push(config.imgUrl + imgArry[i].img)
		}
		uni.previewImage({
			current: i,
			urls: arr,
			indicator: "number",
			loop: true
		})
	}
}

// H5禁止分享等动作
function H5HideShare() {
	function onBridgeReady() {
		WeixinJSBridge.call('hideOptionMenu');
		WeixinJSBridge.call('hideToolbar');
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
}

function setTabBar() {
	uni.setTabBarStyle({
		color: getApp().globalData.color_,
		selectedColor: getApp().globalData.color
	})
	console.log(getApp().globalData.color)
	uni.setNavigationBarColor({
		backgroundColor: getApp().globalData.color
	})

	let num = 1
	uni.setTabBarItem({
		index: 0,
		pagePath: '/pages/home/home',
		text: '首页',
		iconPath: '/static/tabBar/0/1.png',
		selectedIconPath: '/static/tabBar/' + num + '/1.png',
	})

	uni.setTabBarItem({
		index: 1,
		pagePath: '/pages/store/storeMY',
		text: '门店',
		iconPath: '/static/tabBar/0/3.png',
		selectedIconPath: '/static/tabBar/' + num + '/3.png',
	})

	uni.setTabBarItem({
		index: 2,
		pagePath: '/pages/cart/singleCart',
		text: '购物车',
		iconPath: '/static/tabBar/0/7.png',
		selectedIconPath: '/static/tabBar/' + num + '/7.png',
	})

	uni.setTabBarItem({
		index: 3,
		pagePath: '/pages/reserve/reserve',
		text: '预约',
		iconPath: '/static/tabBar/0/6.png',
		selectedIconPath: '/static/tabBar/' + num + '/6.png',
	})

	uni.setTabBarItem({
		index: 4,
		pagePath: '/pages/user/user',
		text: '我的',
		iconPath: '/static/tabBar/0/2.png',
		selectedIconPath: '/static/tabBar/' + num + '/2.png',
	})
}

function imgUrls(imgs) {
	const reg = /^(http|https)/;
	if (!imgs) return;
	if (imgs.search(reg) != -1) return imgs;
	return config.imgUrl + imgs
}

function showLoading(msg) {
	uni.showLoading({
		title: msg,
		mask: true,
	})
}

function hideLoading() {
	uni.hideLoading();
}

function model(title, content = '') {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title,
			content,
			cancelColor: '#cccccc',
			confirmColor: '#DB3801',
			success(res) {
				resolve(res.confirm)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

function setClip(text) {
	if (!text) return;
	uni.setClipboardData({
		data: text,
		success() {
			Toast('复制成功')
		},
		fail(err) {
			console.log(err, 'err');
			Toast('复制失败')
		}
	})
}

function BarTitle(title) {
	uni.setNavigationBarTitle({
		title
	})
}

function openLocation(item) {
	uni.openLocation({
		latitude: Number.parseFloat(item.lat),
		longitude: Number.parseFloat(item.lon),
		name: item.uname,
		address: item.address,
		success() {
			console.log('打开成功');
		},
		fail(err) {
			console.log(err);
			uni.showToast({
				title: "打开失败!",
				icon: 'none',
			})
		}
	})
}

export default {
	richTxt,
	uploadFile,
	uploadFiles,
	Tel,
	call,
	backHome,
	toUrl,
	previewImage,
	timeFormat,
	H5HideShare,
	toGoods,
	setTabBar,
	back,
	showToast,
	Toast,
	imgUrls,
	showLoading,
	hideLoading,
	model,
	setClip,
	BarTitle,
	openLocation
}